package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.util.CookieUtils;
import com.leyou.common.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shkstart
 * @create 2020-05-10 15:59
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("valid")
    public ResponseEntity<Void> valid(String username, String password, HttpServletRequest request, HttpServletResponse response){
        //验证是否登录  登录成功后的 得到token进行加密
       String token = authService.valid(username,password);

        if (token!=null){
            //讲token放进cookie
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60);
            return  ResponseEntity.ok().build();
        }else {
            return ResponseEntity.badRequest().build();
        }

    }


    //验证登录
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN")String token, HttpServletRequest request, HttpServletResponse response){
        //验证用户身份登录  验证有没有token,是否正确
        try {
            UserInfo userinfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            //刷新cookie  延长cookie的时间
            if (userinfo != null){
                //重新生成token  覆盖以前的token加载到cookie中
                String newToken = JwtUtils.generateToken(userinfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
                //讲token放进cookie
                CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),newToken,jwtProperties.getExpire()*60);

                return ResponseEntity.ok(userinfo);
            }


        } catch (Exception e) {
            e.printStackTrace();

        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();

    }


}
